#!/usr/bin/python
# -*- coding: utf8 -*-
import sys, time, json
from threading import Event

from pynput import keyboard
from pynput.keyboard import Key, Controller as KeyboardController
import pydirectinput as dtin

import auto_gaming_utils as utils

# 全局变量
operations = []  # 存储操作记录
pressed_keys = {}
start_time = None  # 记录开始时间
keyboard_controller = KeyboardController()  # 键盘控制对象

TEXT_KEYS = list("`0123456789-=qwertyuiop[]\\asdfghjkl;'zxcvbnm,./")

FUNC_KEY_MAP = {
    Key.alt: 'alt',
    Key.alt_l: 'altleft',
    Key.alt_r: 'altright',
    Key.ctrl: 'ctrl',
    Key.ctrl_l: 'ctrlleft',
    Key.ctrl_r: 'ctrlright',
    Key.shift: 'shift',
    Key.shift_l: 'shiftleft',
    Key.shift_r: 'shiftright',
    Key.cmd: 'win',
    Key.cmd_l: 'winleft',
    Key.cmd_r: 'winright',
    Key.backspace: 'backspace',
    Key.caps_lock: 'capslock',
    Key.up: 'up',
    Key.down: 'down',
    Key.left: 'left',
    Key.right: 'right',
    Key.enter: 'enter',
    Key.esc: 'esc',
    Key.f1: 'f1',
    Key.f2: 'f2',
    Key.f3: 'f3',
    Key.f4: 'f4',
    Key.f5: 'f5',
    Key.f6: 'f6',
    Key.f7: 'f7',
    Key.f8: 'f8',
    Key.f9: 'f9',
    Key.f10: 'f10',
    Key.f11: 'f11',
    Key.f12: 'f12',
    Key.insert: 'insert',
    Key.delete: 'delete',
    Key.home: 'home',
    Key.end: 'end',
    Key.page_down: 'pagedown',
    Key.page_up: 'pageup',
    Key.space: 'space',
    Key.tab: 'tab',
}

def convert_key_enum(key):
    try:
        # 记录字符键（如 'a'、'1'）
        return key.char.lower()
    except AttributeError:
        # 记录功能键（如 Key.ctrl、Key.enter）
        if key in FUNC_KEY_MAP:
            return FUNC_KEY_MAP[key]
        else:
            print("不支持的按键！！！！！！！", key)
    return None

def record_actions(filepath):
    """记录键鼠操作（按 F12 停止记录）"""
    global start_time
    start_time = time.time()
    print("开始记录键鼠操作...")
    print("提示：按 F12 停止记录")

    def on_key_press(key):
        """监听键盘按键（按下）"""

        # 停止条件：按 Ctrl+Shift+S
        if key == Key.f12:
            print("\n停止记录...")
            # 保存记录到文件
            with open(filepath, "w", encoding="utf-8") as f:
                json.dump(operations, f, indent=2)
            print(f"记录完成！共 {len(operations)} 个操作，已保存到 {filepath}")
            # 停止监听
            return False

        key_str = convert_key_enum(key)

        # print('记录按键按下：', key_str)
        if key_str is not None and not key_str in pressed_keys:
            pressed_keys[key_str] = True
            operations.append({
                "type": "key_press",
                "key": key_str,
                "time": time.time() - start_time
            })

    def on_key_release(key):
        """监听键盘按键（按下）"""
        key_str = convert_key_enum(key)

        # print('记录按键松开：', key_str)
        if key_str is not None:
            pressed_keys.pop(key_str)
            operations.append({
                "type": "key_release",
                "key": key_str,
                "time": time.time() - start_time
            })

    keyboard_listener = keyboard.Listener(
        on_press=on_key_press,
        on_release=on_key_release
    )

    keyboard_listener.start()
    keyboard_listener.join()


def replay_actions(filepath):
    """回放键鼠操作"""

    stop_replay = Event()

    # noinspection PyInconsistentReturns
    def on_f12_press(k):
        if k == Key.f12:
            print("\n停止回放...")
            stop_replay.set()
            return False # 停止监听

    keyboard_listener = keyboard.Listener(
        on_press=on_f12_press
    )

    keyboard_listener.daemon = True
    keyboard_listener.start()

    # 读取记录文件
    try:
        with open(filepath, "r", encoding="utf-8") as f:
            action_list = json.load(f)
    except FileNotFoundError:
        print("错误：未找到记录文件", filepath)
        return

    print(f"开始回放 {len(action_list)} 个操作...")
    print("提示：按 F12 紧急终止")

    try:
        last_time = 0.0
        for action in action_list:
            if stop_replay.is_set():
                break
            # 计算当前操作与上一次操作的时间间隔（按速度调整）
            current_time = action["time"]
            utils.precise_sleep(max(0, current_time - last_time))
            last_time = current_time
            key = action["key"]

            if action["type"] == "key_press":
                dtin.keyDown(key)
            elif action["type"] == "key_release":
                dtin.keyUp(key)

    except KeyboardInterrupt:
        print("\n回放已终止")
    except Exception as e:
        print(f"\n回放异常：{e}")


if __name__ == "__main__":

    args = sys.argv[1:]
    if len(args) < 2:
        print("需要两个参数，一个模式，一个文件名")
        sys.exit(1)

    mode, filepath = args
    wait_seconds = 3
    if mode == "replay":
        print(f"{wait_seconds}秒后开始回放：{filepath}")
        time.sleep(wait_seconds)
        print("回放开始")
        replay_actions(filepath)
    elif mode == "record":
        print(f"{wait_seconds}秒后开始记录：{filepath}")
        time.sleep(wait_seconds)
        print("记录开始")
        record_actions(filepath)
    else:
        print("模式参数使用“record”或者“replay”")
        sys.exit(1)